//
//  CustomerDetailWebViewController.m
//  EMMApp
//
//  Created by edz on 2019/8/1.
//  Copyright © 2019 YiXun. All rights reserved.
//

#import "TouristsDetailWebViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import <AVFoundation/AVFoundation.h>
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
#import <MessageUI/MessageUI.h>
#import "KnowViewController.h"
#import "SubscriptionViewController.h"
#import "SignViewController.h"
#import "GetCustomerDetail.h"
#import "CustomerModel.h"
#import "YCXMenu.h"
#import "NewFromViewController.h"
#import "GetConsultantListApi.h"
#import "DistributionConsultantApi.h"


@interface TouristsDetailWebViewController ()<MFMessageComposeViewControllerDelegate,AVAudioPlayerDelegate,ABPeoplePickerNavigationControllerDelegate,UIWebViewDelegate>
{
    ABAddressBookRef addBook;
}
@property (nonatomic,strong) GetCustomerDetail *getCustomerDetail;
@property (nonatomic,strong) UIWebView *webView;
@property (nonatomic,strong) NSURLRequest *urlRequest;
@property (nonatomic,strong) NSMutableArray *itmesNewArr;
@property (nonatomic,strong) NSMutableArray *zyData;
@property (nonatomic,strong) NSMutableArray *zyDataArr;
@end

static NSString *CustomerDetailPath =@"appapi/customer_detail/";

@implementation TouristsDetailWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self postGetConsultantListApi];
    [self postGetCustomerDetailApi];
    [self getPromiseFor_isDistributionCustomer_isAddPaydeposit];
    [self creatNavigationController];
    _zyData = [[NSMutableArray alloc] init];
    _zyDataArr = [[NSMutableArray alloc] init];
}

-(void)setupUI{
    self.webView =[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight)];
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *terminalCode = [IDTools devId2];
    NSString *merchantId = [userdf objectForKey:@"merchantId"];
    NSString *projectId = [userdf objectForKey:@"projectId"];
    NSString *version = apiVString;
    NSString *busNumType = @"11";
    NSString *busNum = @"01";
    NSString *token = [userdf objectForKey:@"is_login"];
    NSString *userId = [userdf objectForKey:@"userNameId"];
    NSString *projectCode = [userdf objectForKey:@"projectCode"];
    
    
    
    
    CustomerModel *paramsModel =[[CustomerModel alloc]init];
    paramsModel.params =[[bodyModel alloc]init];
    paramsModel.params.terminalCode =terminalCode;
    paramsModel.params.merchantId =merchantId;
    paramsModel.params.projectId =projectId;
    paramsModel.params.version =version;
    paramsModel.params.busNumType =busNumType;
    paramsModel.params.busNum =busNum;
    paramsModel.params.token =token;
    paramsModel.params.userId =userId;
    paramsModel.params.projectCode =projectCode;
    
    
    paramsModel.params.customerId =self.customerId;
    NSString *params = [paramsModel toJSONString];
    
    NSString *UrlStr =[NSString stringWithFormat:@"%@/%@?body=%@",apiBaseUrl,CustomerDetailPath,params];
    NSString *destionURL = [UrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *URL =[NSURL URLWithString:destionURL];
    [self.webView loadRequest:[NSURLRequest requestWithURL:URL]];
    self.urlRequest = [NSURLRequest requestWithURL:URL];
}

- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = @"客户详情";
    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"ioc_3"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightClick:)];
    [self.navigationItem setRightBarButtonItem:rightItme];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:CGRectMake(0, 0, 54 ,44)];
    [backBtn addTarget:self
                action:@selector(NewbackToPreviousPage:)
      forControlEvents:UIControlEventTouchUpInside];
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn setImage:[UIImage imageNamed:@"ico_back"] forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    if (EMM_WIDTH <= 320) {
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }else if (EMM_WIDTH > 375){
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    }else{
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *UrlString = request.URL.absoluteString;
    if ([UrlString containsString:@"recruit_list?"]) {
        
        /* 认筹*/
        NSString *customerID = [self getCustomer_WithURL:UrlString];
        [self pushTo_KnowViewController:customerID];
        return NO;
    }else if([UrlString containsString:@"subscription_list?"]){
        
        /* 认购*/
        NSString *customerID = [self getCustomer_WithURL:UrlString];
        [self pushTo_SubscriptionViewController:customerID];
        return NO;
    }else if ([UrlString containsString:@"signing_list?"]){
        
        /* 签约*/
        NSString *customerID = [self getCustomer_WithURL:UrlString];
        [self pushTo_SignViewController:customerID];
        return NO;
    }
    else if ([UrlString containsString:@"call_customer?"]){
        
        /* 打电话*/
        [self btn1Click:nil];
        return NO;
    }
    else if ([UrlString containsString:@"send_sms_customer?"]){
        
        /* 发短信*/
        [self btn2Click:nil];
        return NO;
    }
    else if ([UrlString containsString:@"write_follow?"]){
        /* 写跟进*/
        [self btn3Click:nil];
        return NO;
    }
    
//    else if ([UrlString containsString:@"customer_edit?"]){
//        /* 编辑*/
//        NSString *customerID = self.customerId;
//        [self btn4Click:customerID];
//        return YES;
//    }
    return YES;
    
}

#pragma mark - 返回按钮调用方法
- (void)NewbackToPreviousPage:(id) send {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else if(_isNot == YES){
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(NSString *)getCustomer_WithURL:(NSString *)URL{
    

    NSRange range = [URL rangeOfString:@"?"];
    NSString *paramsString = [URL  substringFromIndex:(range.location+1)];
    NSArray *params =[paramsString componentsSeparatedByString:@"&"];
//    NSMutableArray *resultArray =@[].mutableCopy;
    static NSString *customerId =@"" ;
    
    [params enumerateObjectsUsingBlock:^(NSString *ObjectString, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSDictionary *dict = [self getObjectWithString:ObjectString];
//        [resultArray addObject:dict];
        if ([ObjectString containsString:@"customerId"]) {
            NSString *value =  (NSString *)[dict objectForKey:@"customerId"];
            customerId =[NSString stringWithString:value];
        }
    }];
    
//    NSLog(@"%@",resultArray);
    return customerId;
}




-(NSDictionary *)getObjectWithString:(NSString *)String{
    
    NSMutableDictionary *object =@{}.mutableCopy;
    NSArray *result= [String componentsSeparatedByString:@"="];
    if (result.count==2) {
     [object setValue:[result lastObject] forKey:[result firstObject]];
    }
    return object.copy;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -new 认筹

-(void)pushTo_KnowViewController:(NSString *)customerID{
    KnowViewController *kvc = [[KnowViewController alloc] init];
    kvc.customerId = customerID;
    kvc.getCustomerDetail = _getCustomerDetail;
    kvc.paymentMethod = _getCustomerDetail.rqPaymentMethod;
    [self.navigationController pushViewController:kvc animated:YES];
    [kvc setNewCustomersBlock:^{
        [self.webView reload];
    }];
}
#pragma mark - 认购
-(void)pushTo_SubscriptionViewController:(NSString *)customerID{
    SubscriptionViewController *kvc = [[SubscriptionViewController alloc] init];
    kvc.customerId = customerID;
    kvc.getCustomerDetail = _getCustomerDetail;
    kvc.paymentMethod = _getCustomerDetail.rqPaymentMethod;
    [self.navigationController pushViewController:kvc animated:YES];
    [kvc setNewCustomersBlock:^{
        [self.webView reload];
    }];
}
#pragma mark - 签约
-(void)pushTo_SignViewController:(NSString *)customerID{
    SignViewController *kvc = [[SignViewController alloc] init];
    kvc.customerId = customerID;
    kvc.getCustomerDetail = _getCustomerDetail;
    kvc.paymentMethod = _getCustomerDetail.rqPaymentMethod;
    [self.navigationController pushViewController:kvc animated:YES];
    [kvc setNewCustomersBlock:^{
         [self.webView reload];
    }];
}



#pragma mark -打电话
- (void)btn1Click:(UIButton *)btn {

    [self postGetUserCallListApi];
}

#pragma mark -发短信
- (void)btn2Click:(UIButton *)btn {
    NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:_getCustomerDetail.customerPhone, nil];
    [self creatinitWithGetNoteArr:arr];
}
#pragma mark -写跟进
- (void)btn3Click:(UIButton *)btn {
    FollowUpViewController *fvc = [[FollowUpViewController alloc] init];
    fvc.customerId = _customerId;
    [self.navigationController pushViewController:fvc animated:YES];
    [fvc setFollowUpViewBlock:^{
        
    }];
}
#pragma mark -编辑
- (void)btn4Click:(NSString *)customerId {
    
//    fvc.isflg = YES;
//    fvc.getCustomerDetail = _getCustomerDetail;
//    fvc.customerId = customerId;
//    [self.navigationController pushViewController:fvc animated:YES];
//    [fvc setNewCustomersBlock:^{
//        [self.webView reload];
//    }];
}


- (void)creatinitWithGetNoteArr:(NSMutableArray *)dxArr {
    
    if( [MFMessageComposeViewController canSendText] ){
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc]init];
        controller.recipients = dxArr;
        //        controller.body = @"测试发短信";
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:^{
            
        }];
        [[[[controller viewControllers] lastObject] navigationItem] setTitle:nil];//修改短信界面标题
    }else{
        [self alertWithTitle:@"提示信息" msg:@"设备没有短信功能"];
    }
}
#pragma mark - MFMessageComposeViewControllerDelegate发短信协议代理方法调用
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    [controller dismissViewControllerAnimated:NO completion:^{
    }];
    switch ( result ) {
        case MessageComposeResultCancelled:
            [self alertWithTitle:@"提示信息" msg:@"发送取消"];
            break;
        case MessageComposeResultFailed:// send failed
            [self alertWithTitle:@"提示信息" msg:@"发送失败"];
            break;
        case MessageComposeResultSent:
            [self alertWithTitle:@"提示信息" msg:@"发送成功"];
            break;
        default:
            break;
    }
}

#pragma mark - api查看客户详情
- (void)postGetCustomerDetailApi {
    
    GetCustomerDetailApi *api = [[GetCustomerDetailApi alloc] initWithCustomerId:self.customerId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetCustomerDetailApi *result = (GetCustomerDetailApi *)request;
        if (result.isSuccess) {
            GetCustomerDetail *get = result.resultData;
            _getCustomerDetail = get;
            

        }
        [self hideHud];
        

    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma maek - 电话平台调用方法

- (void)postGetUserCallListApi {
    [self showHudInWindow:@"正在加载中..."];
    GetUserCallListApi *api = [[GetUserCallListApi alloc] initWith];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetUserCallListApi *result = (GetUserCallListApi *)request;
        //请求成功
        if (result.isSuccess) {
            GetUserCallList *get = result.resultData;
            
            if ([NSString isStringEmpty2:get.isPhoneInformation] == NO) {
                if ([get.isPhoneInformation isEqualToString:@"0"]) {
                    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_getCustomerDetail.customerPhone];
                    UIWebView * callWebview = [[UIWebView alloc] init];
                    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                    [self.view addSubview:callWebview];
                }else {
                    UserCallMenuView *userListV = [[UserCallMenuView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT) title:@"选择拨打号码" nameArr:get.userCallList];
                    userListV.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
                    [[UIApplication sharedApplication].keyWindow addSubview:userListV];
                    __weak UserCallMenuView *weakMenuView = userListV;
                    [userListV setTouchUserCallMenuViewBlock:^(NSString *telePhone, NSString *telePhoneType) {
                        NSLog(@"%@-%@",telePhone,telePhoneType);
                        if ([NSString isStringEmpty2:telePhone] == NO) {
                            [self postGetCallBackApiTelePhoneString:telePhone];
                        }
                        [weakMenuView removeFromSuperview];
                    }];
                }
            }else {
                NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_getCustomerDetail.customerPhone];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
            }
        } else {
            
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}


- (void)postGetCallBackApiTelePhoneString:(NSString *)telePhoneString {
    GetCallBackApi *api = [[GetCallBackApi alloc] initWithCustomerId:self.customerId caller:telePhoneString called:_getCustomerDetail.customerPhone terminalModel:@"0" terminalModelId:self.customerId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetCallBackApi *result = (GetCallBackApi *)request;
        //请求成功
        if (result.isSuccess) {
            GetCallBack *get = result.resultData;
            FollowUpViewController *fvc = [[FollowUpViewController alloc] init];
            fvc.customerId = self.customerId;
            fvc.followId = get.followId;
            [self.navigationController pushViewController:fvc animated:YES];
            [fvc setFollowUpViewBlock:^{
            }];
        } else {
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

-(void )getPromiseFor_isDistributionCustomer_isAddPaydeposit{
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *isDistributionCustomer = [userdf objectForKey:@"isDistributionCustomer"];
    NSString *isAddPaydeposit = [userdf objectForKey:@"isAddPaydeposit"];
    _itmesNewArr = [@[
                      [YCXMenuItem menuItem:@"添加到通讯录"
                                      image:[UIImage imageNamed:@"more_message"]
                                        tag:100
                                   userInfo:nil],
                      ] mutableCopy];
    if ([isAddPaydeposit isEqualToString:@"1"]) {//新增认筹-0、未开通；1、已开通
        [_itmesNewArr addObject:[YCXMenuItem menuItem:@"新增认筹"
                                                image:[UIImage imageNamed:@"more_form"]
                                                  tag:100
                                             userInfo:nil]];
    }
    if ([isDistributionCustomer isEqualToString:@"1"]) {//客户分配-0、未开通；1、已开通
        [_itmesNewArr addObject: [YCXMenuItem menuItem:@"分配"
                                                 image:[UIImage imageNamed:@"more_allot"]
                                                   tag:100
                                              userInfo:nil]];
    }
}



- (void)rightClick:(UIButton *)btn {
    [YCXMenu setTintColor:[UIColor colorFromHexCode:@"#FB5B3B"]];
    [YCXMenu setSelectedColor:[UIColor colorFromHexCode:@"#FB5B3B"]];
    [YCXMenu setSeparatorColor:[UIColor colorFromHexCode:@"#CCCCCC"]];
    [YCXMenu setTitleFont:[UIFont systemFontOfSize:15]];
    if ([YCXMenu isShow]){
        [YCXMenu dismissMenu];
    } else {
        [YCXMenu showMenuInView:self.view fromRect:CGRectMake(self.view.frame.size.width - 55, 0, 50, 0) menuItems:_itmesNewArr selected:^(NSInteger index, YCXMenuItem *item) {
            [self creatYCXMenuShowUI:index];
        }];
    }
}

#pragma mark - 右按钮弹出框

- (void)creatYCXMenuShowUI:(NSInteger)index {
    if (index == 0) {
        
        [self creatPhoneAdd];
    }else if (index == 1) {
        
        NewFromViewController *nvc = [[NewFromViewController alloc] init];
        nvc.isFrom = @"0";
        nvc.customerId = self.customerId;
        [self.navigationController pushViewController:nvc animated:YES];
    }else if (index == 2){
        
        ShowMenuView *menuView = [[ShowMenuView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) title:@"选项" titleNmae:@"经纪人" numLits:nil items:_zyDataArr];
        menuView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        [[UIApplication sharedApplication].keyWindow addSubview:menuView];
        __weak ShowMenuView *weakMenuView = menuView;
        [menuView setTouchBlock:^(NSString *indet,NSString *numStrring) {
            NSLog(@"%@",indet);
            if ([NSString isStringEmpty2:indet] == NO) {
                ConsultantList *consList = [_zyData objectAtIndex:[numStrring intValue]-1];
                NSString *consultantId = consList.consultantUserId;
                NSArray *arr = @[@{@"customerId":_customerId}];
                [self postDistributionConsultantApiConsultantUserId:consultantId customerList:arr];
            }
            [weakMenuView removeFromSuperview];
            
        }];
    }
}

#pragma mark - 增加用户信息到手机通讯录
- (void)creatPhoneAdd {
    [self getAddressBook];
    [self AddPeopleWithFirstName:_getCustomerDetail.customerName WithLastName:nil  withPhoneNum:_getCustomerDetail.customerPhone ];
}

-(void)AddPeopleWithFirstName:(NSString *)firstName WithLastName:(NSString *)lastName withPhoneNum:(NSString *)phoneNum {
    ABRecordRef person = ABPersonCreate();
    //        NSString *firstName = @"粉丝";
    //        NSString *lastName = @"001";
    // 电话号码数组
    //NSArray *phones = [NSArray arrayWithObjects:@"1234",@"456",nil];
    NSArray *phones = [NSArray arrayWithObjects:phoneNum,nil];
    
    // 电话号码对应的名称
    //    NSArray *labels = [NSArray arrayWithObjects:@"iphone",@"home",nil];
    NSArray *labels = [NSArray arrayWithObjects:@"iphone",nil];
    
    //这里的字段和上面的字段完全相同
    // 设置名字属性
    ABRecordSetValue(person, kABPersonFirstNameProperty,(__bridge CFStringRef)firstName, NULL);
    // 设置姓氏属性
    ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFStringRef)lastName, NULL);
    // 设置生日属性
    // ABRecordSetValue(person, kABPersonBirthdayProperty,(__bridge CFDateRef)birthday, NULL);
    // 字典引用
    ABMultiValueRef dic =ABMultiValueCreateMutable(kABMultiStringPropertyType);
    // 添加电话号码与其对应的名称内容
    for (int i = 0; i < [phones count]; i ++) {
        ABMultiValueIdentifier obj = ABMultiValueAddValueAndLabel(dic,(__bridge CFStringRef)[phones objectAtIndex:i], (__bridge CFStringRef)[labels objectAtIndex:i], &obj);
    }
    // 设置phone属性
    ABRecordSetValue(person, kABPersonPhoneProperty, dic, NULL);
    
    //为联系人添加头像
    UIImage *image =  [UIImage imageNamed:@"img07"];
    ABPersonSetImageData (person,(__bridge CFDataRef)UIImagePNGRepresentation(image),nil);
    
    // 将新建的联系人添加到通讯录中
    ABAddressBookAddRecord(addBook, person, NULL);
    // 保存通讯录数据
    ABAddressBookSave(addBook, NULL);
}

-(void)getAddressBook{
    int __block tip=0;
    //声明一个通讯簿的引用
    addBook =nil;
    //因为在IOS6.0之后和之前的权限申请方式有所差别，这里做个判断
    if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        //创建通讯簿的引用
        addBook=ABAddressBookCreateWithOptions(NULL, NULL);
        //创建一个出事信号量为0的信号
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        //申请访问权限
        ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error)        {
            //greanted为YES是表示用户允许，否则为不允许
            if (!greanted) {
                tip=1;
            }
            //发送一次信号
            dispatch_semaphore_signal(sema);
        });
        //等待信号触发
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        //IOS6之前
        addBook =ABAddressBookCreate();
    }
    if (tip) {
        //做一个友好的提示
        [self showToast:@"添加失败"];
        return;
    }else {
        [self showToast:@"添加成功"];
    }
    
}

- (void)postDistributionConsultantApiConsultantUserId:(NSString *)consultantUserId customerList:(NSArray *)customerList {
    
    DistributionConsultantApi *api = [[DistributionConsultantApi alloc] initWithConsultantUserId:consultantUserId customerList:customerList];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        DistributionConsultantApi *result = (DistributionConsultantApi *)request;
        if (result.isSuccess) {
            //            DistributionConsultant *get = result.resultData;
            [self showToast:@"分配成功"];
        } else {
            [self showToast:result.resultData.errorMsg];
            
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma  mark - 经纪人
- (void)postGetConsultantListApi{
    [_zyDataArr removeAllObjects];
    [_zyData removeAllObjects];
    GetConsultantListApi *api = [[GetConsultantListApi alloc] initWithResourcesCode:nil searchType:nil];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetConsultantListApi *result = (GetConsultantListApi *)request;
        if (result.isSuccess) {
            GetConsultantList *get = result.resultData;
//            _getConsultantList = get;
            for (ConsultantList *list in get.consultantList) {
                [_zyDataArr addObject:list.consultantUserName];
                [_zyData addObject:list];
                
            }
        } else {
            //            [self showToast:result.resultData.errorMsg];
            
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
    }];
}

@end
